/* 
 * File:   repository_tree_model.cpp
 * Author: jolo
 * 
 * Created on: 11. Oktober 2011, 12:24
 * Lincense: New BSD License (The BSD 2-Clause License)
 */

#include "repository_tree_model.hpp"

#include <QtGui/QApplication>

#include <boost/foreach.hpp>

#include <model/repository.hpp>

#include <widgets/entity_item.hpp>

#include <gui/project_editor_dialog.hpp>

#include "repository_item.hpp"
#include "main_window.hpp"

namespace gui
{

    repository_tree_model::repository_tree_model(QObject* p)
    : widgets::tree_model(model::repository_ptr(), p)
    {
        on_repository_closed();
    }

    repository_tree_model::~repository_tree_model()
    {
    }

    void repository_tree_model::on_repository_closed()
    {

    }

    void repository_tree_model::on_repository_opened(model::repository_ptr r)
    {
        set_root_entity(r);
        
        clear();
        
        QStringList lbls;
        lbls << tr("Objects");

        setHorizontalHeaderLabels(lbls);
        
        QStandardItem* ri = new gui::repository_item(r);
        invisibleRootItem()->appendRow(ri);
        
        emit reloaded();
    }
    
    model::repository_ptr repository_tree_model::get_repository() {
        return dynamic_pointer_cast<model::repository>(get_root_entity());
    }
    
    void repository_tree_model::on_create_request(widgets::entity_item* itm) {
        dynamic_pointer_cast<model::chemical_element>(itm->entity());
        dynamic_pointer_cast<model::project>(itm->entity());
        
        model::project_ptr buf(get_repository()->create_project(tr("New Project").toStdString()));
        project_editor_dialog* dlg = new project_editor_dialog(buf, QApplication::activeWindow());
        dlg->exec();
    }
    
    void repository_tree_model::on_edit_request(widgets::entity_item* itm) {
        std::cout << "edit: " << *(itm->entity()) << std::endl;
    }
    
    void repository_tree_model::on_delete_request(widgets::entity_item* itm) {
        std::cout << "delete: " << *(itm->entity()) << std::endl;
    }
}
